#!/usr/bin/python
# -*-  coding: utf-8  -*-
from django.utils.safestring import mark_safe
from django.utils.html import escape
from pprint import pprint

class AnswerAggragator(object):
    factories = {}
    def __init__(self, question, answers):
        self.answers = answers

    def register(cls, type, factory):
        cls.factories[type] = factory
    register = classmethod(register)

    def create(cls, question, answers):
        return cls.factories[question.type](question, answers)
    create = classmethod(create)

    def output(self):
        raise NotImplementedError()

class TextAnswerAggragator(AnswerAggragator):
    def __init__(self, question, answers):
        super(TextAnswerAggragator, self).__init__(question, answers)

    def output(self):
        r = ['<ul>'] + ['<ol>' + escape(a.answer) + '</ol>' for a in self.answers] + ['</ul>']
        pprint(r)
        return mark_safe(''.join(r))

AnswerAggragator.register('T', TextAnswerAggragator)

class ChoiceAnswerAggragator(AnswerAggragator):
    def __init__(self, question, answers):
        super(ChoiceAnswerAggragator, self).__init__(question, answers)
        self.choices = question.surveychoice_set.all()
        self.result = {}
        for c in self.choices:
            self.result[str(c.index)] = 0
        for a in answers:
            self.result[a.answer] += 1

    def output(self):
        width = 480
        height = 360
        type = 'p'
        data = ','.join([str(self.result[str(c.index)]) for c in self.choices])
        label = '|'.join(['%s(%d)' % (c.label, self.result[str(c.index)]) for c in self.choices])
        return mark_safe('<img src="http://chart.apis.google.com/chart?chs=%dx%d&chco=3366CC&cht=%s&chd=t:%s&chdl=%s" width="%d" height="%d" alt="" />' % \
                (width, height, type, data, label, width, height))

AnswerAggragator.register('S', ChoiceAnswerAggragator)
AnswerAggragator.register('R', ChoiceAnswerAggragator)

class CommentAnswerAggragator(AnswerAggragator):
    def __init__(self, question, answers):
        super(CommentAnswerAggragator, self).__init__(question, answers)

    def output(self):
        return mark_safe(''.join(['<p class="comment">' + escape(a.answer) + '</p>' for a in self.answers]))

AnswerAggragator.register('C', CommentAnswerAggragator)

